﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sofire.DataComm.Net.Async;
using Sofire.DataComm;
using Sofire.DataComm.Net;

namespace DataCommTest.AsyncTest
{
    public class AsyncClientTestDemo : ITest
    {
        AsyncSocketClient Client;
        public AsyncClientTestDemo()
        {
            this.Client = new AsyncSocketClient("client", new SocketInfo(ProtocolMode.Tcp, "localhost", 9595));
            this.Client.StateChanged += new CommunicationStateEventHandler(Client_StateChanged);
            this.Client.SocketFaild += new AsyncSocketExceptionEventHandler(Client_SocketFaild);
            this.Client.AsyncReceive += new AsyncSocketReceiveEventHandler(Client_AsyncReceive);
        }

        void Client_AsyncReceive(object sender, AsyncSocketReceiveEventArgs e)
        {
            if(e.Mode == ReceiveMode.Full)
            {
                var s = e.GetString();
                Console.WriteLine("收到响应：" + s);
                e.Remote.Send("请求已经收到！");
            }
        }

        void Client_SocketFaild(object sender, AsyncSocketExceptionEventArgs e)
        {
            Console.WriteLine("服务器 {0} 发生了错误（{1}）...", e.Socket.RemoteEndPoint, e.Exception);
        }

        void Client_StateChanged(object sender, CommunicationStateEventArgs e)
        {
            if(e.State == CommunicationState.Failed)
                Console.WriteLine("客户端异常 {0} ...", (e as CommunicationFailedStateEventArgs).Exception);
            else
                Console.WriteLine("客户端状态 {0} ...", e.State);
        }

        public void Test()
        {
            this.Client.Open();
            if(this.Client.IsRunning)
            {
                this.Client.Send("你好，我叫张三。");
            }
        }

        ~AsyncClientTestDemo()
        {
            this.Client.Close();
        }

    }
}
